package com.rongshu.view.mediaPlayer.manager;

import android.media.MediaPlayer;

import com.rongshu.view.mediaPlayer.bean.AudiobookDetailsResponse;
import com.rongshu.view.mediaPlayer.bean.PlayEvent;
import com.rongshu.view.mediaPlayer.emnu.MediaState;
import com.rongshu.view.mediaPlayer.emnu.PlayAction;
import com.rongshu.view.mediaPlayer.emnu.PlayMode;
import com.rongshu.view.mediaPlayer.listener.AudiobookPlayListener;
import com.utils.LogUtil;
import com.widget.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * created by zhengweis on 2019/4/22.
 * description：
 */
public class PlayerManager implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
    private static PlayerManager player = null;
    private AudiobookPlayer mMediaPlayer;
    private List<AudiobookDetailsResponse.ResponseBean> mQueue;
    private int mQueueIndex;
    private PlayMode mPlayMode;
    private AudiobookDetailsResponse.ResponseBean currentMedia;
    private AudiobookPlayListener listener;

    public static PlayerManager getPlayer() {
        if (player == null) {
            player = new PlayerManager();
        }
        return player;
    }

    public PlayerManager() {
        mMediaPlayer = new AudiobookPlayer();
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mQueue = new ArrayList<>();
        mQueueIndex = 0;
        //默认为列表循环模式
        mPlayMode = PlayMode.LOOP;
    }

    /**
     * 设置音频数据
     *
     * @param queue 数据
     * @param index 初始播放位置
     */
    public void setQueue(List<AudiobookDetailsResponse.ResponseBean> queue, int index) {
        mQueue = queue;
        mQueueIndex = index;
        play(getNowPlaying());
    }

    /**
     * 设置音频数据
     *
     * @param song 数据
     */
    public void setQueue(AudiobookDetailsResponse.ResponseBean song) {
        mQueue = null;
        mQueueIndex = 0;
        currentMedia = song;
        play(currentMedia);
    }

    /**
     * 播放
     *
     * @param song
     */
    public void play(AudiobookDetailsResponse.ResponseBean song) {
        if (song == null) {
            ToastUtils.show("没有可播放的音频文件");
            return;
        }
        if (listener != null) {
            listener.mediaPrepare();
        }
        try {
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(song.getMp3Url());
            mMediaPlayer.prepareAsync();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    LogUtil.d("mediaPlayer -- ready");
                    if (listener != null) {
                        listener.mediaReady();
                    }
                    start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 继续
     */
    public void start() {
        if (getDuration() != 0 && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        }
    }

    /**
     * 暂停
     */
    public void pause() {
        if (getDuration() != 0 && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
        }
    }

    /**
     * 停止
     */
    public void stop() {
        mMediaPlayer.stop();
        mMediaPlayer.reset();
        mMediaPlayer.release();
        player = null;
    }

    /**
     * 释放
     */
    public void release() {
        mMediaPlayer.stop();
        mMediaPlayer.reset();
    }

    /**
     * 下一首
     */
    public void next() {
        if (getNextSong() == null) {
            ToastUtils.show("没有可播放的音频文件了");
        } else {
            play(getNextSong());
        }
    }

    /**
     * 上一首
     */
    public void previous() {
        if (getPreviousSong() == null) {
            ToastUtils.show("没有可播放的音频文件了");
        } else {
            play(getPreviousSong());
        }
    }

    // TODO: 2019/4/22 当前音频播放完毕， 暂时不不开放播放下一个音频功能
    @Override
    public void onCompletion(MediaPlayer mp) {
        LogUtil.d("mediaPlayer -- onCompletion");
        mp.reset();
        PlayEvent event = new PlayEvent();
        event.setAction(PlayAction.OVER);
        EventBus.getDefault().post(event);
//        next();
    }

    // 因为直接切歌(其他)会发生错误，所以增加错误监听器。返回true。就不会回调onCompletion方法了。
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        LogUtil.d("mediaPlayer -- onError");
        return true;
    }

    /**
     * 获取当前播放的音频
     */
    public AudiobookDetailsResponse.ResponseBean getNowPlaying() {
        if (mQueue != null && mQueue.size() > 0) {
            return mQueue.get(mQueueIndex);
        }
        if (currentMedia != null) {
            return currentMedia;
        }
        return null;
    }

    /**
     * 获取下一个带播放的音频
     */
    private AudiobookDetailsResponse.ResponseBean getNextSong() {
        if (mQueue.isEmpty()) {
            return null;
        }
        switch (mPlayMode) {
            case LOOP:
                return mQueue.get(getNextIndex());
            case RANDOM:
                return mQueue.get(getRandomIndex());
            case REPEAT:
                return mQueue.get(mQueueIndex);
        }
        return null;
    }

    /**
     * 获取上一个带播放的音频
     */
    private AudiobookDetailsResponse.ResponseBean getPreviousSong() {
        if (mQueue.isEmpty()) {
            return null;
        }
        switch (mPlayMode) {
            case LOOP:
                return mQueue.get(getPreviousIndex());
            case RANDOM:
                return mQueue.get(getRandomIndex());
            case REPEAT:
                return mQueue.get(mQueueIndex);
        }
        return null;
    }

    /**
     * 当前音频的已播放时长
     */
    public int getCurrentPosition() {
        if (getNowPlaying() != null) {
            return mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    /**
     * 当前音频总时长
     *
     * @return
     */
    public int getDuration() {
        if (getNowPlaying() != null) {
            return mMediaPlayer.getDuration();
        }
        return 0;
    }

    /**
     * 指定播放到某进度
     */
    public void seekTo(int time) {
        mMediaPlayer.seekTo(time);
    }

    /**
     * 当前播放状态
     */
    public MediaState getMediaState() {
        return mMediaPlayer.getState();
    }

    /**
     * 当前播放模式
     */
    public PlayMode getPlayMode() {
        return mPlayMode;
    }

    /**
     * 设置播放模式
     */
    public void setPlayMode(PlayMode playMode) {
        mPlayMode = playMode;
    }

    private int getNextIndex() {
        mQueueIndex = (mQueueIndex + 1) % mQueue.size();
        return mQueueIndex;
    }

    private int getPreviousIndex() {
        mQueueIndex = (mQueueIndex - 1) % mQueue.size();
        return mQueueIndex;
    }

    private int getRandomIndex() {
        mQueueIndex = new Random().nextInt(mQueue.size()) % mQueue.size();
        return mQueueIndex;
    }

    /**
     * 音频是否正在播放
     */
    public boolean isPlaying() {
        return mMediaPlayer.isPlaying();
    }

    /**
     * 设置缓冲监听
     */
    public void setPlayListener(AudiobookPlayListener listener) {
        this.listener = listener;
    }

    /**
     * 清除回调
     */
    public void clearListener() {
        listener = null;
    }
}
